<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单据编号" prop="refundNo">
        <el-input
          v-model="queryParams.refundNo"
          placeholder="请输入单据编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['purchasing:refund:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['purchasing:refund:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['purchasing:refund:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['purchasing:refund:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="refundList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="供应商" align="center" prop="supplier" />
      <el-table-column label="单据编号" align="center" prop="refundNo" />
      <el-table-column label="商品信息" align="center" prop="merchandiseNews" />
      <el-table-column label="单据日期" align="center" prop="refundTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.refundTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="operator" />
      <el-table-column label="退款金额" align="center" prop="refundPrice" />
      <el-table-column label="实际退款" align="center" prop="actualRefund" />
      <el-table-column label="状态" align="center" prop="refundState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pur_refund_state" :value="scope.row.refundState"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="handleUpdateRefundState(scope.row)"
            v-hasPermi="['purchasing:order:edit']"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['purchasing:refund:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['purchasing:refund:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改配置对话框 -->
    <el-dialog title="关联采购订单" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form"  label-width="100px" :inline="true" style="width: 100%;padding: 20px">

        &emsp;&emsp;&emsp;
        <el-form-item>
          <el-button icon="el-icon-search" @click="showGoodsListDialog" size="mini">选择商品</el-button>
        </el-form-item>

        <div style="border-top: 1px solid #e0e0e0;margin-top:20px;margin-bottom:20px" @change="getTotal"></div>

        <el-table   :data="selectOrdersList" >
          <el-table-column label="供应商"  prop="supplier">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.pru_shop" :value="scope.row.supplier"/>
            </template>
          </el-table-column>
          <el-table-column label="单号" prop="orderNumber"  />
          <el-table-column label="单据日期"  prop="orderTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作员" prop="operator"  />
          <el-table-column label="总价" prop="aggregateAmount"  />
          <el-table-column label="优惠" prop="discounts"  />
          <el-table-column label="实付金额" prop="discountsAmount"  />
          <el-table-column label="状态" align="center" prop="orderState">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.pru_order_state" :value="scope.row.orderState"/>
            </template>
          </el-table-column>
        </el-table>
        <br/>
        <div style="width: 100%">
          <el-input  type="textarea" v-model="form.remark" placeholder="订单备注" />
        </div>
        <br/>
        <el-form-item label="结算账户" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择结算账户">
            <el-option
              v-for="dict in dict.type.pru_user"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单总额" prop="allAggregateAmount">
          <el-input v-model="form.allAggregateAmount"  placeholder="" size="mini"/>
        </el-form-item>
        <el-form-item label="优惠金额" prop="allDiscounts">
          <el-input v-model="form.allDiscounts" value="0"  placeholder="" size="mini"/>
        </el-form-item>
        <el-form-item label="实际退款" prop="allEarnest">
          <el-input v-model="form.actualRefund" @change="getTotal3" placeholder="" size="mini"/>
        </el-form-item>
        <el-form-item label="本次欠款" prop="debt">
          <el-input v-model="form.debt" placeholder="" size="mini"/>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button type="primary" @click="submitForm2">添加并审核</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 选择商品的弹窗 -->
    <el-dialog title="选择要入库的订单" :visible.sync="goodsListOpen" width="1000px" append-to-body>

      <el-table  ref="goodsTable"  :data="ordersList" @selection-change="handleGoodsSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <<el-table-column label="供应商"  prop="supplier">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pru_shop" :value="scope.row.supplier"/>
        </template>
      </el-table-column>
        <el-table-column label="单号" prop="orderNumber"  />
        <el-table-column label="单据日期"  prop="orderTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.orderTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作员" prop="operator"  />
        <el-table-column label="总价" prop="aggregateAmount"  />
        <el-table-column label="优惠" prop="discounts"  />
        <el-table-column label="实付金额" prop="discountsAmount"  />
        <el-table-column label="状态" align="center" prop="orderState">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.pru_order_state" :value="scope.row.orderState"/>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary"  @click="goodsListOpen = false">确定选择</el-button>
        <el-button @click="goodsListDialogCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRefund, getRefund, delRefund, addRefund, updateRefund ,changeRefundState} from "@/api/purchasing/refund";
import {listWarehouse} from "@/api/purchasing/warehouse";
import {getOrderByStateToRefund} from "@/api/purchasing/order";
import {addEntry, changeEntryState} from "@/api/purchasing/entry";


export default {
  name: "Refund",
  dicts: ['pru_user','pru_order_state', 'pru_shop', 'pru_order_state','pur_refund_state'],
  data() {
    return {
      //仓库集合
      warehouse:[],
      goodsListOpen : false,
      //选中的数据
      ordersList:[],
      //所有以审核未入库的采购订单
      selectOrdersList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购退货表格数据
      refundList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        supplier: null,
        entryNumber: null,
        merchandiseNews: null,
        entryTime: null,
        operator: null,
        allAggregateAmount: null,
        debt: null,
        payment: null,
        orderState: null,
        allEarnest: null,
        userId: null,
        warehouseId: null,
        allDiscounts: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 审核按钮操作 */
    handleUpdateRefundState(row) {
      this.reset();
      const refundId = row.refundId || this.ids
      changeRefundState(refundId).then(response => {
        this.$modal.msgSuccess("审核成功");
        this.getList();
      });
    },
    // 计算总价
    getTotal(){
      this.form.allAggregateAmount = 0;

      this.getTotal1();

      for(var i=0;i<this.selectOrdersList.length;i++){
        this.form.allAggregateAmount+=this.selectOrdersList[i].aggregateAmount
      }
      return this.form.allAggregateAmount
    },

    getTotal1(){
      this.form.allDiscounts = 0;
      for(var i=0;i<this.selectOrdersList.length;i++){
        this.form.allDiscounts+=this.selectOrdersList[i].discounts
      }
      return this.form.allDiscounts
    },

    getTotal2(){
      this.form.refundPrice =this.form.allAggregateAmount-this.form.allDiscounts ;
    },


    getTotal3(){
      this.form.debt = 0;
      this.form.debt=this.form.allAggregateAmount-this.form.allDiscounts-this.form.actualRefund;
      return this.form.debt
    },
    getWarehouse(){
      listWarehouse(null).then(response => {
        this.warehouse = response.rows;
      });
    },
    getOrderList(){
      getOrderByStateToRefund().then(response => {
        this.ordersList = response.data;
      });
    },
    goodsListDialogCancel(){
      this.goodsListOpen = false;
      this.selectOrdersList = [];
      this.$refs.goodsTable.clearSelection();
    },
    // 多选框选中数据
    handleGoodsSelectionChange(selection){
      this.selectOrdersList = selection;
      this.getTotal();

    },
    showGoodsListDialog(){
      this.goodsListOpen = true;
      this.getOrderList();
    },
    /** 查询采购退货列表 */
    getList() {
      this.loading = true;
      listRefund(this.queryParams).then(response => {
        this.refundList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        refundId: null,
        supplier: null,
        refundNo: null,
        merchandiseNews: null,
        refundTime: null,
        operator: null,
        refundPrice: null,
        actualRefund: null,
        refundState: 1,
        userId: null,
        allAggregateAmount: null,
        allDiscounts: null,
        warehouseId: null,
        debt: null,
        remake: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.refundId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购退货";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const refundId = row.refundId || this.ids
      getRefund(refundId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购退货";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.refundId != null) {
            updateRefund(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.refundState=1;
            this.form.orderList=this.selectOrdersList;
            this.getTotal2();
            addRefund(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 提交按钮 */
    submitForm2() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.getTotal2();
          this.form.refundState=2;
          this.form.orderList=this.selectOrdersList;
          addEntry(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });

        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const refundIds = row.refundId || this.ids;
      this.$modal.confirm('是否确认删除采购退货编号为"' + refundIds + '"的数据项？').then(function() {
        return delRefund(refundIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('purchasing/refund/export', {
        ...this.queryParams
      }, `refund_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
